<!--
 * Copyright (c) 2013-Now http://jeesite.com All rights reserved.
 * No deletion without permission, or be held responsible to law.
 * @author PR
-->
<template>
  <BasicDrawer
    v-bind="$attrs"
    :showFooter="true"
    :okAuth="'card:kstLsProCardDataH:edit'"
    @register="registerDrawer"
    @ok="handleSubmit"
    width="80%"
  >
    <template #title>
      <Icon :icon="getTitle.icon" class="pr-1 m-1" />
      <span> {{ getTitle.value }} </span>
    </template>
    <BasicForm @register="registerForm">
      <template #kstLsProCardDataCList>
        <BasicTable
          @register="registerKstLsProCardDataCTable"
          @row-click="handleKstLsProCardDataCRowClick"
        />
        <a-button class="mt-2" @click="handleKstLsProCardDataCAdd" v-auth="'card:kstLsProCardDataH:edit'">
          <Icon icon="ant-design:plus-circle-outlined" /> {{ t('新增') }}
        </a-button>
      </template>
    </BasicForm>
  </BasicDrawer>
</template>
<script lang="ts">
  export default defineComponent({
    name: 'ViewsCardKstLsProCardDataHForm',
  });
</script>
<script lang="ts" setup>
  import { defineComponent, ref, computed } from 'vue';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { router } from '/@/router';
  import { Icon } from '/@/components/Icon';
  import { BasicForm, FormSchema, useForm } from '/@/components/Form';
  import { BasicTable, useTable } from '/@/components/Table';
  import { BasicDrawer, useDrawerInner } from '/@/components/Drawer';
  import { KstLsProCardDataH, kstLsProCardDataHSave, kstLsProCardDataHForm } from '/@/api/mes/card/kstLsProCardDataH';

  const emit = defineEmits(['success', 'register']);

  const { t } = useI18n('card.kstLsProCardDataH');
  const { showMessage } = useMessage();
  const record = ref<KstLsProCardDataH>({} as KstLsProCardDataH);
  const getTitle = computed(() => ({
    icon: router.currentRoute.value.meta.icon || 'ant-design:book-outlined',
    value: record.value.isNewRecord ? t('新增拉手工艺参数') : t('编辑拉手工艺参数'),
  }));

  const inputFormSchemas: FormSchema[] = [
    {
      label: t('编号'),
      field: 'code',
      component: 'Input',
      componentProps: {
        maxlength: 64,
      },
    },
    {
      label: t('版本号'),
      field: 'verNum',
      component: 'Input',
      componentProps: {
        maxlength: 64,
      },
    },
    {
      label: t('备注'),
      field: 'remarks',
      component: 'InputTextArea',
      componentProps: {
        maxlength: 500,
      },
      colProps: { lg: 24, md: 24 },
    },
    {
      label: t(''),
      field: 'kstLsProCardDataCList',
      component: 'Input',
      colProps: { lg: 24, md: 24 },
      slot: 'kstLsProCardDataCList',
    },
  ];

  const [registerForm, { resetFields, setFieldsValue, updateSchema, validate }] = useForm({
    labelWidth: 120,
    schemas: inputFormSchemas,
    baseColProps: { lg: 12, md: 24 },
  });

  const [registerKstLsProCardDataCTable, kstLsProCardDataCTable] = useTable({
    actionColumn: {
      width: 60,
      actions: (record: Recordable) => [
        {
          icon: 'ant-design:delete-outlined',
          color: 'error',
          popConfirm: {
            title: '是否确认删除',
            confirm: handleKstLsProCardDataCDelete.bind(this, record),
          },
          auth: 'card:kstLsProCardDataH:edit',
        },
      ],
    },
    rowKey: 'id',
    pagination: false,
    bordered: true,
    size: 'small',
    inset: true,
  });

  async function setKstLsProCardDataCTableData(_res: Recordable) {
    kstLsProCardDataCTable.setColumns([
      {
        title: t('工序号'),
        dataIndex: 'gwName',
        width: 130,
        align: 'left',
        editRow: false,
        editComponent: 'Input',
        editComponentProps: {
          maxlength: 200,
        },
        editRule: false,
      },
      {
        title: t('采集点名称'),
        dataIndex: 'tagname',
        width: 130,
        align: 'left',
        editRow: false,
        editComponent: 'Input',
        editComponentProps: {
          maxlength: 200,
        },
        editRule: false,
      },
      {
        title: t('设定值'),
        dataIndex: 'setVal',
        width: 130,
        align: 'left',
        editRow: true,
        editComponent: 'Input',
        editComponentProps: {
          maxlength: 200,
        },
        editRule: false,
      },
      {
        title: t('实际值'),
        dataIndex: 'actVal',
        width: 130,
        align: 'left',
        editRow: false,
        editComponent: 'Input',
        editComponentProps: {
          maxlength: 200,
        },
        editRule: false,
      },
    ]);
    kstLsProCardDataCTable.setTableData(record.value.kstLsProCardDataCList || []);
  }

  function handleKstLsProCardDataCRowClick(record: Recordable) {
    record.onEdit?.(true, false);
  }

  function handleKstLsProCardDataCAdd() {
    kstLsProCardDataCTable.insertTableDataRecord({
      id: new Date().getTime(),
      isNewRecord: true,
      editable: true,
    });
  }

  function handleKstLsProCardDataCDelete(record: Recordable) {
    kstLsProCardDataCTable.deleteTableDataRecord(record);
  }

  async function getKstLsProCardDataCList() {
    let kstLsProCardDataCListValid = true;
    let kstLsProCardDataCList: Recordable[] = [];
    for (const record of kstLsProCardDataCTable.getDataSource()) {
      if (!(await record.onEdit?.(false, true))) {
        kstLsProCardDataCListValid = false;
      }
      kstLsProCardDataCList.push({
        ...record,
        id: !!record.isNewRecord ? '' : record.id,
      });
    }
    for (const record of kstLsProCardDataCTable.getDelDataSource()) {
      if (!!record.isNewRecord) continue;
      kstLsProCardDataCList.push({
        ...record,
        status: '1',
      });
    }
    if (!kstLsProCardDataCListValid) {
      throw { errorFields: [{ name: ['kstLsProCardDataCList'] }] };
    }
    return kstLsProCardDataCList;
  }

  const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
    setDrawerProps({ loading: true });
    await resetFields();
    const res = await kstLsProCardDataHForm(data);
    record.value = (res.kstLsProCardDataH || {}) as KstLsProCardDataH;
    record.value.__t = new Date().getTime();
    setFieldsValue(record.value);
    setKstLsProCardDataCTableData(res);
    updateSchema([
      {
        field: 'code',
        componentProps: {
          disabled: !record.value.isNewRecord,
        },
      },
    ]);
    setDrawerProps({ loading: false });
  });

  async function handleSubmit() {
    try {
      const data = await validate();
      setDrawerProps({ confirmLoading: true });
      const params: any = {
        isNewRecord: record.value.isNewRecord,
        code: record.value.code,
      };
      data.kstLsProCardDataCList = await getKstLsProCardDataCList();
      // console.log('submit', params, data, record);
      const res = await kstLsProCardDataHSave(params, data);
      showMessage(res.message);
      setTimeout(closeDrawer);
      emit('success', data);
    } catch (error: any) {
      if (error && error.errorFields) {
        showMessage(t('您填写的信息有误，请根据提示修正。'));
      }
      console.log('error', error);
    } finally {
      setDrawerProps({ confirmLoading: false });
    }
  }
</script>
